<template>
  <div>
    <div class="user-group-page">
      <!-- aside -->
      <div class="manage-page-aside">
        <div class="head-section" style="margin-bottom: 10px;">
          <h3 class="table-head">网点人员分组：</h3>
          <el-select @change="selectOrganChange" v-model="organId" placeholder="请选择" value-key="item">
            <el-option v-for="item in organOptions" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </div>
        <div class="head-section" style="overflow: hidden;">

          <h3 class="table-head">组列表</h3>
          <header>
            <el-button type="primary" plain @click="handelAddGroup" size="medium">新增
            </el-button>
            <el-button type="primary" plain @click="handelModifyGroup" size="medium">编辑
            </el-button>
            <el-button type="primary" plain @click="handelDeleteGroup" size="medium">删除
            </el-button>
          </header>
        </div>
        <div class="table-section">
          <el-scrollbar wrap-class="scrollbar-wrapper" style="height:100%">
            <el-table ref="refGroupTable" :data="groupTableData" border highlight-current-row
              :row-class-name="tableRowClassName" @row-click="handleCurrentChange">
              <el-table-column type="index" label="序号" width="60">
              </el-table-column>
              <el-table-column prop="groupName" label="组名"></el-table-column>


            </el-table>
          </el-scrollbar>
        </div>
      </div>

      <!-- content -->
      <div class="page-right manage-page-content">
        <!-- 包含用户 -->
        <div class="userList-section">
          <div class="head-section">
            <h3 class="table-head">包含的用户</h3>
            <header>
              <!--                           <div class="buttons">-->
              <el-button type="primary" plain size="medium" @click="handelAddGroupUser">添加
              </el-button>
              <el-button type="primary" plain size="medium" @click="handleDeleteGroupUser">移除
              </el-button>
              <!--                           </div>-->
            </header>
          </div>
          <div class="user-table">
            <!-- <el-scrollbar wrap-class="scrollbar-wrapper" style="height:100%"> -->
            <el-table :data="groupUserTableData" border height="430" @selection-change="handleUserChange">
              <el-table-column type="selection" width="40"></el-table-column>
              <el-table-column type="index" label="序号" width="50">
              </el-table-column>
              <el-table-column prop="userName" label="用户名">
              </el-table-column>
              <!-- <el-table-column prop="name" label="姓名"></el-table-column>
                            <el-table-column prop="status" label="状态">
                                <template slot-scope="scope">
                                    <span>{{ scope.row.status == 'Y' ? '正常' : '禁用' }}</span>
                                </template>
                            </el-table-column> -->
            </el-table>
            <!-- </el-scrollbar> -->
          </div>
        </div>

        <!-- 区域列表 -->
        <div class="areaList-section">
          <div class="head-section">
            <h3 class="table-head">管理的区域</h3>
            <header class="section-head clearfix">
              <!--                            <div class="buttons">-->
              <el-button type="primary" size="medium" plain @click="handelAddGroupArea">添加
              </el-button>
              <el-button type="primary" size="medium" plain @click="handelDeleteGroupArea">移除
              </el-button>
              <!--                            </div>-->
            </header>
          </div>
          <div class="table">
            <el-table :data="areaTableData" border height="430" @selection-change="handleSelectionAreaChange">
              <el-table-column type="selection" width="40"></el-table-column>
              <el-table-column type="index" label="序号" width="50">
              </el-table-column>
              <el-table-column prop="areaName" label="区域" width="295">
              </el-table-column>
              <el-table-column label="电器类型">
                <template slot-scope="scope">
                  <el-checkbox-group :min="1" v-model="scope.row.targetCategoryIds" >
                    <!-- @change="
                    (val) => {
                      checkboxTargetCateGory(val, scope.row)
                    }
                  " -->
                    <el-checkbox v-for="item in channelTargetCategory" :key="item.id" :label="
                      scope.row.targetCategoryIds.indexOf(0) != -1
                        ? 0
                        : item.id
                    ">
                      {{ item.name }}
                    </el-checkbox>
                  </el-checkbox-group>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </div>

      <!-- 新增用户组弹窗 -->
      <el-dialog class="same-dia" :title="isNewGroup ? '新增用户组' : '编辑用户组'" :visible.sync="dialogGroupVisible"
        width="500px" @close="resetForm" :close-on-click-modal="false">
        <el-form ref="pojoForm" :rules="rules" :model="pojoGroup" label-width="100px">
          <el-form-item label="组名：" prop="groupName">
            <el-input v-model="pojoGroup.groupName" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button v-if="isNewGroup" type="primary" @click="addGroupSubmit('pojoForm')">确 定
          </el-button>
          <el-button v-else type="primary" @click="modifyGroupSubmit('pojoForm')">确 定
          </el-button>
          <el-button @click="dialogGroupVisible = false">取 消</el-button>
        </div>
      </el-dialog>

      <!-- 新增组包含的用户 -->
      <el-dialog class="same-dia" title="添加用户" :visible.sync="dialogGroupUserVisible" width="400px"
        :close-on-click-modal="false" @close="groupUserClose">
        <el-input v-model="userSearch" size="mini" placeholder="输入用户名搜索" style="margin-bottom:10px" />
        <el-table :data="
          GroupUserDialogData.filter(
            (data) =>
              !userSearch ||
              data.name.toLowerCase().includes(userSearch.toLowerCase())
          )
        " border ref="multipleTable" height="350" @selection-change="handleAvailableUserChange">
          <el-table-column type="selection" width="60"></el-table-column>
          <el-table-column type="index" label="序号" width="80"></el-table-column>
          <el-table-column prop="name" label="用户名"></el-table-column>
        </el-table>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="addGroupUserSubmit">确 定
          </el-button>
          <el-button @click="dialogGroupUserVisible = false">取 消</el-button>
        </div>
      </el-dialog>

      <!-- 新增组管理的区域 -->
      <el-dialog class="same-dia" title="添加管理区域" :visible.sync="dialogGroupAreaVisible" width="500px"
        :close-on-click-modal="false">
        <div class="equipment-title">
          <h4 style="margin-right: 20px; display: inline-block; min-width: 56px">
            设备类型
          </h4>
          <el-checkbox-group v-model="targetCategoryId">
            <el-checkbox v-for="item in channelTargetCategory" :key="item.id" :label="item.id">
              {{ item.name }}
            </el-checkbox>
          </el-checkbox-group>
        </div>
        <el-tree :data="areaTreeData" ref="refdialogAreaTree" show-checkbox node-key="id" :props="defaultProps"
          @check="dialogTreeChange">
        </el-tree>
        <div slot="footer" class="dialog-footer" style="text-align: center">
          <el-button type="primary" @click="addGroupAreaSubmit">确 定
          </el-button>
          <el-button @click="dialogGroupAreaVisible = false">取 消</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import ajax from '@/utils/ajax'
import { tableSelection, deleteConfirm } from '@/utils/elementui'
import axios from "axios";
export default {
  data() {
    return {
      permission: {
        add: false,
        modify: false,
        delete: false,
        add_user: false,
        delete_user: false,
        add_area: false,
        delete_area: false,

        has_role: false,
        available_role: false,
        role_add: false,
        role_delete: false,
      },
      groupTableData: [],
      tableIndex: 0,
      customerId: null,
      currentGroupId: null,
      currentGroupInfo: null,

      // 新增组
      dialogGroupVisible: false,
      pojoGroup: {
        organId: '',
        groupName: '',

      },
      rules: {
        groupName: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
      },

      // 包含的用户
      AllUserTableData: [],
      groupUserTableData: [],
      dialogGroupUserVisible: false,
      GroupUserDialogData: [],
      mulAvailableUserSelection: [],
      mulUserSecection: [],
      userSearch: '',

      // 管理的区域
      dialogGroupAreaVisible: false,
      isNewGroup: true,
      isAddGroupUser: true,
      areaTableData: [],
      channelTargetCategory: [],
      organOptions: [],
      currentOrganValue: '',
      organId: null,
      areaTreeData: [],
      targetCategoryId: [],
      defaultProps: {
        label: 'name',
      },
      checkTreeAreaNode: [],
      mulAreaSelection: [],
    }
  },
  created() {
    this.customerId = this.$store.getters.customerId
    this.getOrganListData()
    // this.setPermission()
    this.getUserListData()
    this.getTargetCategoryData()
  },
  mounted() {
    this.$store.dispatch('actions/dynamicTitleAction', this.$route.meta.title)
  },
  methods: {
    // 设置可操作的权限
    setPermission() {
      let role_permissions = this.$store.getters.rolePermissions
      for (let item of role_permissions) {
        if (item.action === '/web/user_group') {
          for (let permission of item.privilegeList) {
            switch (permission.action) {
              case '/web/user_group/add':
                this.permission.add = true
                break
              case '/web/user_group/modify':
                this.permission.modify = true
                break
              case '/web/user_group/delete':
                this.permission.delete = true
                break
              case '/web/user_group/add_user':
                this.permission.add_user = true
                break
              case '/web/user_group/delete_user':
                this.permission.delete_user = true
                break
              case '/web/user_group/add_area':
                this.permission.add_area = true
                break
              case '/web/user_group/delete_area':
                this.permission.delete_area = true
                break

              default:
                break
            }
          }
        }
      }
    },

    // 获取用户列表
    getUserListData() {
      let pocustomerId = this.customerId;

      ajax.get({
        url: this.$API.getUserListByCustomerId + pocustomerId,

        success: (response) => {
          //console.log(response)

          this.AllUserTableData = response.data;
        },
        error: (res) => {
          //console.log(res)
          this.$message({
            message: res.message,
            type: "error",
          });
        },
      });
    },
    // 获取所有网点信息
    getOrganListData() {
      ajax.get({
        url: this.$API.getUserOrgan + this.$store.getters.user.id,
        success: (response) => {
          const resp = response.data;
          if (resp.length > 0) {
            this.organOptions = resp;
            this.organId = resp[0].id
            this.getGroupData()
          } else {
            this.organOptions = [];
          }
        },
        error: (res) => {
          this.$message({
            message: res.message,
            type: "error",
          });
        },
      });
    },
    //选择网点
    selectOrganChange(value) {
      this.organId = value
      this.tableIndex = 0
      this.getGroupData()
    },
    //获得组信息
    getGroupData() {
      ajax.post({
        url: this.$API.usergroupList + this.organId,
        success: (res) => {
          let resp = res.data
          this.groupTableData = resp
          if (resp.length > 0) {
            this.$nextTick(() => {
              let index = this.tableIndex
              this.$refs.refGroupTable.setCurrentRow(
                this.$refs.refGroupTable.data[index]
              )
              this.currentGroupId = this.groupTableData[index].id
              this.currentGroupInfo = this.groupTableData[index]
              this.getGroupUserData()
              this.getGroupAreaData()
            })
          }
          else {
            this.groupUserTableData = []
            this.areaTableData = []
            this.currentGroupId=null
            this.currentGroupInfo=null
          }
        },
      })
    },
    // table每行加上index
    tableRowClassName({ row, rowIndex }) {
      row.index = rowIndex
    },
    //选择组改变区域用户数据
    handleCurrentChange(val) {
      this.currentGroupInfo = val
      this.currentGroupId = val.id
      this.tableIndex = val.index
      this.getGroupUserData()
      this.getGroupAreaData()
    },

    //新增组
    handelAddGroup() {
      this.dialogGroupVisible = true
      this.isNewGroup = true
    },
    trusteeship(row) {

      ajax.post({
        url: this.$API.setGroupTargetAreaDelegated,
        data: { groupId: this.currentGroupId, areaId: row.areaId, delegated: row.delegated },
        // data:{id:77},
        success: (response) => {
          this.$message({
            message: '设置成功',
            type: 'success',
          })
        },
        error: (res) => {

          row.delegated = '1'
          this.$message({
            message: res.message,
            type: 'error',
          })
        },
      })
    },
    //提交增加组
    addGroupSubmit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.pojoGroup.organId = this.organId
          ajax.post({
            url: this.$API.createUserGroup,
            data: this.pojoGroup,
            success: (response) => {
              this.getGroupData()
              this.dialogGroupVisible = false
              this.$message({
                message: response.message,
                type: 'success',
              })
            },
            error: (res) => {
              this.$message({
                message: res.message,
                type: 'error',
              })
            },
          })
        }
      })
    },

    //修改组信息
    handelModifyGroup() {
      if (this.currentGroupInfo) {
        this.isNewGroup = false
        this.dialogGroupVisible = true
        this.$nextTick(() => {
          this.pojoGroup.groupName = this.currentGroupInfo.groupName

          this.pojoGroup.organId = this.currentGroupInfo.organId
          this.pojoGroup.id = this.currentGroupInfo.id
        })
      } else {
        this.$message({
          message: '请先选择要编辑的用户组',
          type: 'warning',
        })
      }
    },
    //提交修改组信息
    modifyGroupSubmit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          ajax.post({
            url: this.$API.modifyUserGroup + this.currentGroupInfo.id,
            data: this.pojoGroup,
            success: (response) => {
              this.getGroupData()
              this.dialogGroupVisible = false
              this.$message({
                message: response.message,
                type: 'success',
              })
            },
            error: (res) => {
              this.$message({
                message: res.message,
                type: 'error',
              })
            },
          })
        }
      })
    },

    //删除组信息
    handelDeleteGroup() {
      if (this.currentGroupInfo) {
        deleteConfirm(this).then((res) => {
          if (res) {
            ajax.post({
              url: this.$API.deleteUserGroup + this.currentGroupId,
              success: (response) => {
                this.tableIndex = 0
                this.getGroupData()
                this.$message({
                  message: response.message,
                  type: 'success',
                })
              },
              error: (response) => {
                this.$message({
                  message: response.message,
                  type: 'error',
                })
              },
            })
          }
        })
      } else {
        this.$message({
          message: '请先选择要删除的用户组',
          type: 'warning',
        })
      }
    },

    //获取包含的用户
    getGroupUserData() {
      ajax.post({
        url: this.$API.groupUserList + this.currentGroupId,
        success: (res) => {
          this.groupUserTableData = res.data
        },
      })
    },
    //新增组包含的用户
    handelAddGroupUser() {
      if (this.currentGroupId !== null) {
        this.dialogGroupUserVisible = true
        this.isAddGroupUser = true
        if (this.groupUserTableData.length > 0) {

          let useridlist = []
          this.groupUserTableData.forEach(data => {
            useridlist.push(data.userId)
          })

          let useridattr = new Set(useridlist);
          let alluseridattr = new Set(this.AllUserTableData);
          let filteralluser = new Set([...alluseridattr].filter(item => !useridattr.has(item.id)));
          this.GroupUserDialogData = [...filteralluser]
        } else {
          this.GroupUserDialogData = this.AllUserTableData
        }

      } else {
        this.$message({
          message: '请选择分组',
          type: 'warning',
        })
      }
    },
    //选择组内用户
    handleAvailableUserChange(val) {
      this.mulAvailableUserSelection = val
    },
    // 提交新增的包含的用户
    addGroupUserSubmit() {
      let mulAvailableUserSelection = this.mulAvailableUserSelection
      let idList = []
      let self = this
      for (let i in mulAvailableUserSelection) {
        let attr = {}
        attr.groupId = this.currentGroupId
        attr.userId = mulAvailableUserSelection[i].id
        attr.organId = this.organId
        attr.remark = ""
        idList.push(attr)
      }
      axios
        .post(this.$API.addUserToGroupBatch, idList)
        .then(function (res) {

          if (res.data.success) {
            self.getGroupUserData()
            self.$message({
              message: "添加用户成功",
              type: "success",
            });
            self.dialogGroupUserVisible = false
          }
        });

    },

    // 选择要删除的用户
    handleUserChange(value) {
      // console.log(value)
      this.mulUserSecection = value
    },
    //提交删除组的数据
    handleDeleteGroupUser() {
      let selectionArr = this.mulUserSecection
      let selResult = tableSelection(selectionArr, 0)
      let self = this
      if (selResult) {
        deleteConfirm(this).then((res) => {
          if (res) {
            axios
              .post(this.$API.delUserFromGroupBatch, selectionArr)
              .then(function (res) {
                if (res.data.success) {
                  self.getGroupUserData()
                  self.$message({
                    message: "删除用户成功",
                    type: "success",
                  });
                }
              });
          }
        })
      }
    },

    //获取组内区域信息
    getGroupAreaData() {
      ajax.post({
        url: this.$API.groupTargetList + this.currentGroupId,
        success: (response) => {
          console.log(response)
          const resp = response.data
          for (let item of resp) {
            let arr = []
            if (item.targetCategoryId.indexOf(0) != -1) {

              for (let j of this.channelTargetCategory) {
                arr.push(j.id)
              }
            }
            else {
              let targetlist = item.targetCategoryId.split(",")
              for (let item of targetlist) {
                arr.push(parseInt(item))
              }

            }
            item.targetCategoryIds = arr
          }
          console.log(resp)
          console.log(this.channelTargetCategory)
          this.areaTableData = resp
        },
      })
    },
    // 获取所有通道类型数据
    getTargetCategoryData() {
      ajax.get({
        url: this.$API.getDictTargetCategoryList,
        data: {},
        success: (response) => {
          //console.log(response)
          this.channelTargetCategory = response.data;
          // 
        },
        error: (res) => {
          //console.log(res)
          this.$message({
            message: res.message,
            type: "error",
          });
        },
      });
    },
    //处理复选框选中
    checkValue(row, targetCategoryDataId) {
      // console.log(row, targetCategoryDataId)
      if (row.targetCategoryIds.indexOf(0) != -1) {
        return true
      }
      if (row.targetCategoryIds.indexOf(targetCategoryDataId) != -1) {
        return true
      }
    },

    //选择区域的电器
    checkboxTargetCateGory(value, rowData) {
      let po_id = this.currentGroupId
      let po_areaId = rowData.areaId
      let po_targetCategoryId = value.join(',')
      ajax.post({
        url: this.$API.deleteTargetCategory,
        data: {
          id: po_id,
          areaId: po_areaId,
          targetCategoryId: po_targetCategoryId,
        },
        showLoading: false,
        success: (response) => {
          if (response.success) {
            this.getGroupAreaData()
            this.$message({
              message: response.message,
              type: 'success',
            })
          }
        },
        error: (res) => {
          this.$message({
            message: res.message,
            type: 'error',
          })
        },
      })
    },

    // 添加组内区域
    handelAddGroupArea() {
      if (this.currentGroupId !== null) {
        this.dialogGroupAreaVisible = true
        this.checkTreeAreaNode = []

        if (this.organId) {
          this.getAreaListData()
        }
      } else {
        this.$message({
          message: '请选择分组',
          type: 'warning',
        })
      }
    },

    //获取可选择区域列表数据
    getAreaListData() {
      ajax.post({
        url: this.$API.getGroupTargetUnBind + this.currentGroupId,
        success: (response) => {
          this.areaTreeData = response.data
        },
        error: (res) => {
          //console.log(res)
          this.$message({
            message: res.message,
            type: "error",
          });
        },
      });
    },
    // 点击树的复选框
    dialogTreeChange() {
      let checkArr = this.$refs.refdialogAreaTree.getCheckedNodes()
      this.checkTreeAreaNode = checkArr
      console.log(this.checkTreeAreaNode)
    },
    //提交添加组内区域
    addGroupAreaSubmit() {


      if (this.checkTreeAreaNode.length == 0) {
        this.$message({
          message: '请先选择区域',
          type: 'warning',
        })
        return
      }
      // for (let item of ) {
      //   // if (item.areas.length == 0) {
      //   idsArr.push(item.id)
      //   // }
      // }
      // let po_ids = idsArr.join(',')
      let idList = []
      let self = this
      for (let i of this.checkTreeAreaNode) {
        let attr = {}
        attr.areaName = i.name
        attr.areaId = i.id
        attr.organId = i.organId
        attr.groupId = this.currentGroupId
        attr.targetCategoryId = this.targetCategoryId.join(',')
        idList.push(attr)
      }
      axios
        .post(this.$API.addGroupTargetBatch, idList)
        .then(function (res) {
          if (res.data.success) {
            self.dialogGroupAreaVisible = false

            self.getGroupAreaData()
            self.$message({
              message: '新增成功',
              type: 'success',
            })
          }
        });

    },

    //选择要删除的区域Ids
    handleSelectionAreaChange(value) {
      this.mulAreaSelection = value
    },
    //删除组内区域
    handelDeleteGroupArea() {
      let selectionArr = this.mulAreaSelection
      let selResult = tableSelection(selectionArr, 0)
       let self = this
       let ids=[]
       for(let item of selectionArr)
       {
        ids.push(item.id)
       }
      if (selResult) {
        deleteConfirm(this).then((res) => {
          if (res) {
            axios
              .post(this.$API.delGroupTargetBatch, ids)
              .then(function (res) {
                if (res.data.success) {
                  self.dialogGroupAreaVisible = false

                  self.getGroupAreaData()
                  self.$message({
                    message: ' 删除成功',
                    type: 'success',
                  })
                }
              });
          }
        })
      }
    },

    groupUserClose() {
      this.userSearch = ''
    },
    // 重置表单
    resetForm() {
      this.$refs['pojoForm'].resetFields()
    },
  },
}
</script>

<style lang="stylus" scoped>
    @import "~@/assets/styles/variables.styl";
>>>
    .user-group-page
        position absolute
        top 0
        left 0
        right 0
        bottom 0
        padding 0.2rem
        overflow auto
        .head-section
            .table-head
                /*margin-top 0.2rem*/
                height 0.4rem
                line-height 0.4rem
                font-size 0.16rem
                font-weight normal
                float left
            header
                float right
        .table-section
            position absolute
            top 1.16rem
            left 0.2rem
            right 0.2rem
            bottom 0.2rem

        .manage-page-aside .el-table__body tr
            cursor pointer

        .page-right
            .section-head
                position relative
                margin-bottom: 0.1rem

                .head-title
                    position absolute
                    bottom 0
                    display: inline-block
                    float: left
                    font-size: 0.16rem
                    font-weight: normal

            .areaList-section
                margin-top: 0.2rem

    .el-table__body tr.current-row > td
        color: #fff
        background-color: rgba(68, 199, 244, 0.2) !important

    .el-table .el-checkbox__label
        color #fff

    .el-dialog .el-select
        width auto

    .el-checkbox__input.is-disabled.is-checked .el-checkbox__inner
        background-color: #409EFF
        border-color: #409EFF

    /*@media screen and (max-width 1440px)*/
    /*    .table-section*/
    /*        top 1.2rem !important*/
>>>.el-switch__label {
    color:#fff}
>>>.el-switch__label.is-active {
    color: #fff;
}
    >>> .same-dia {
        .el-form .el-form-item:last-child {
            margin-bottom: 0
        }

        .el-dialog__footer {
            padding: 0 0.3rem 0.3rem
        }
    }
.equipment-title {
  display: flex;
  margin-bottom: 10px;
}

>>>.equipment-title .el-checkbox__label {
  color: #fff;
}
>>>.equipment-title .el-checkbox{
    min-width: 81px;
    margin-right: 10px;}
</style>
